using KenEgozi.Com.Domain.Aggregates.Common;
using Castle.MonoRail.Framework;
using Rhino.Commons;
using System.Web;
using System.IO;

namespace KenEgozi.Com.Weblog.Controllers
{
	[Layout("Default")]
	public class FilesController : SmartDispatcherController
	{
		[Cache(HttpCacheability.NoCache)]
		public void Download(string filename)
		{
			CancelView();
			CancelLayout();
			string filePath =
				Context.ApplicationPhysicalPath +
				"\\Content\\Binary\\" +
				filename;
			if (!File.Exists(filePath))
			{
				Response.StatusCode = 404;
				RenderText("File not found");
				return;
			}
			Download download = new Download(filename, Context.UnderlyingContext.Request.UserHostAddress);
			HttpCookie cookie = Context.UnderlyingContext.Request.Cookies["commenterData"];
			if (cookie != null && cookie.HasKeys)
			{
				download.SetUserData(cookie.Values["Name"],cookie.Values["Email"],cookie.Values["Homepage"]);
			}

			With.Transaction(delegate
         	{
         		Repository<Download>.Save(download);
			});
			string fileUrl = 
				Context.ApplicationPath + "/content/binary/" + filename;

			Redirect(fileUrl);
		}
	}
}
